package root.electronclass.electronclass.school

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import root.electronclass.electronclass.common.base.BasicAdapter
import root.electronclass.electronclass.common.base.BindingHolder
import root.electronclass.electronclass.common.base.ViewBindingFragment
import root.electronclass.electronclass.common.util.HeadUtil
import root.electronclass.electronclass.mvp.GlobalParameter
import root.electronclass.electronclass.mvp.base.BaseResponse
import root.electronclass.electronclass.mvp.base.CallbackNext
import root.electronclass.electronclass.mvp.entity.*
import root.electronclass.electronclass.mvp.rest.RestManager
import root.electronclass.electronclass.databinding.*
import root.electronclass.electronclass.other.PictureActivity
import root.electronclass.electronclass.school.model.SchoolNotificationModel
import retrofit2.Call
import root.electronclass.electronclass.adapter.GridSpacingItemDecoration
import root.electronclass.electronclass.ext.startFragment


/**
 *
 */
class SchoolInfoFragment : ViewBindingFragment<FragmentSchoolInfoBinding>() {
    private val viewModel: SchoolNotificationModel by viewModels()
    private val schoolInfoVO: OrgSchoolInfoVO = GlobalParameter.getSchoolInfo()
    private var pro = 0
    private var picList = arrayListOf<String>()


    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden.not() && view != null) {
            getSchoolInfo()
            initSchoolLeaderRecyclerView()
            initSchoolDirectorRecyclerView()
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding.schoolSystem.text = schoolInfoVO.schoolType
        binding.schoolNature.text = schoolInfoVO.schoolNature
        binding.schoolPersonNum.text = schoolInfoVO.studentCount.toString()
        binding.schoolTeacherNum.text = schoolInfoVO.teacherCount.toString()
        showWaitingMessage()
        initSchoolInfoRecyclerView()
        initSchoolLeaderRecyclerView()
        initSchoolStyleRecyclerView()
        binding.directorRecycler.addItemDecoration(GridSpacingItemDecoration(3, 16))
        initSchoolDirectorRecyclerView()
        binding.tvLeaderMore.setOnClickListener {
            startActivity(Intent(requireActivity(), SchoolHonorActivity::class.java))
        }
        binding.tvDirectorMore.setOnClickListener {
            startFragment(SchoolDirectorFragment::class.java)
        }
        binding.tvStyleMore.setOnClickListener {
            startActivity(Intent(requireActivity(), SchoolStyleActivity::class.java))
        }
    }


    private fun getSchoolInfo() {
        RestManager.getInstance().initRest().schoolInfo()
            .enqueue(object : CallbackNext<BaseResponse<OrgSchoolInfoVO>>(mDialogViewModel) {

                override fun onSuccessful(
                    call: Call<BaseResponse<OrgSchoolInfoVO>>,
                    response: BaseResponse<OrgSchoolInfoVO>
                ) {
                    if (response.isSuccess) {
                        GlobalParameter.setSchoolInfo(response.rows)
                        initSchoolStyleRecyclerView()
                    }
                }

                override fun onError(
                    call: Call<BaseResponse<OrgSchoolInfoVO>>,
                    response: BaseResponse<OrgSchoolInfoVO>
                ) {

                }
            })
    }


    private fun initSchoolInfoRecyclerView() {
        binding.motto.text = schoolInfoVO.motto ?: "-"
        binding.introduction.text = schoolInfoVO.introduction ?: "-"
        binding.bxtj.text = schoolInfoVO.bxtj ?: "-"
    }

    private fun initSchoolLeaderRecyclerView() {
        binding.leaderRecycler.layoutManager =
            LinearLayoutManager(requireActivity(), LinearLayoutManager.HORIZONTAL, false)
        binding.leaderRecycler.adapter = adapter
        viewModel.rcHonor.observe(requireActivity()) {
            adapter.replaceAll(it)
            dismissProgress(pro + 50)
        }
        viewModel.rcHonorList()
    }

    private val adapter = object : BasicAdapter<RcHonor, ItemSchoolInfoTeacherBinding>() {
        override fun onBindViewHolder(
            holder: BindingHolder<ItemSchoolInfoTeacherBinding>,
            item: RcHonor?
        ) {
            holder.binding.pic.setImageURI(item?.imgUrlFormat?.get(0)?.url)
            holder.binding.name.text = item?.name
        }
    }

    private fun initSchoolStyleRecyclerView() {

        val adapter = object : BasicAdapter<SchoolPicDto, ItemSchoolStylePicBinding>() {
            override fun onBindViewHolder(
                holder: BindingHolder<ItemSchoolStylePicBinding>,
                item: SchoolPicDto?
            ) {
                holder.binding.picName.text = item?.name
                holder.binding.picSw.setImageURI(item?.url)
                holder.binding.item.setOnClickListener {
                    PictureActivity.startActivity(activity!!, picList, holder.adapterPosition)
                }
            }
        }
        if (schoolInfoVO.picJsonFormat.size > 0) {
            for (pic in schoolInfoVO.picJsonFormat) {
                picList.add(pic.url)
            }
        }
        binding.schoolStyleRecycler.layoutManager =
            LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
        binding.schoolStyleRecycler.adapter = adapter
        if (schoolInfoVO.picJsonFormat != null && schoolInfoVO.picJsonFormat.size > 0) {
            adapter.refresh(schoolInfoVO.picJsonFormat)
        }

    }

    private fun initSchoolDirectorRecyclerView() {
        val dto = TeacherDto()
        dto.isRealName = 1
        RestManager.getInstance().initRest().teacherInfo(dto).enqueue(object :
            CallbackNext<BaseResponse<List<UserInfoTeacherVO>>>(mDialogViewModel) {
            override fun onSuccessful(
                call: Call<BaseResponse<List<UserInfoTeacherVO>>>,
                response: BaseResponse<List<UserInfoTeacherVO>>
            ) {
                if (response.isSuccess) {
                    val adapter =
                        object : BasicAdapter<UserInfoTeacherVO, ItemSchoolDirectorBinding>() {
                            override fun onBindViewHolder(
                                holder: BindingHolder<ItemSchoolDirectorBinding>,
                                item: UserInfoTeacherVO?
                            ) {
                                if (item?.userInfoVo?.facePhotoFormat.orEmpty().isEmpty()) {
                                    holder.binding.headIv.setActualImageResource(
                                        HeadUtil.getHeadPic(
                                            if (item?.gender == 1) 1 else 0
                                        )
                                    )
                                } else {
                                    // 设置默认的失败图
                                    holder.binding.headIv.hierarchy.setFailureImage(HeadUtil.getHeadPic(if (item?.gender == 1) 1 else 0))

                                    // 设置图片URI
                                    val imageUrl = item?.userInfoVo?.facePhotoFormat?.get(0)?.url
                                    if (!imageUrl.isNullOrEmpty()) {
                                        holder.binding.headIv.setImageURI(imageUrl)
                                    } else {
                                        // 如果没有有效的URL，可以选择保留失败图
                                        holder.binding.headIv.setImageURI("") // 可选，保留失败图
                                    }
                                }
                                holder.binding.name.text = item?.name

                            }
                        }
                    binding.directorRecycler.adapter = adapter
                    binding.directorRecycler.layoutManager = GridLayoutManager(activity, 3)
                    adapter.refresh(if (response.rows.size > 8) {
                        response.rows.take(8) // 如果超过8条，只显示前8条
                    } else {
                        response.rows // 如果低于或等于8条，显示全部
                    })
                    dismissProgress(pro + 50)
                }
            }

            override fun onError(
                call: Call<BaseResponse<List<UserInfoTeacherVO>>>,
                response: BaseResponse<List<UserInfoTeacherVO>>
            ) {
                dismissProgress()
            }
        })

        //获取教师总数
        RestManager.getInstance().initRest().teacherCount()
            .enqueue(object : CallbackNext<BaseResponse<Any>>(mDialogViewModel) {
                override fun onSuccessful(
                    call: Call<BaseResponse<Any>>,
                    response: BaseResponse<Any>
                ) {
                    "合计：${response.rows}人".also { binding.tvDirectorUnm.text = it }
                }

                override fun onError(call: Call<BaseResponse<Any>>?, response: BaseResponse<Any>?) {
                }
            })


    }


}